package com.myyun.yun.service.serviceImpl;

import com.myyun.yun.domain.User;
import com.myyun.yun.mapper.UserMapper;
import com.myyun.yun.service.UserService;
import com.myyun.yun.utils.CommonUtils;
import com.myyun.yun.utils.JWTUtils;
import com.sun.xml.internal.ws.api.message.HeaderList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author CC小天才
 * @website www.flyskill.cn
 * @date 2021/9/11 16:24
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired(required = false)
    private UserMapper userMapper;

    @Override
    public int save(Map<String, String> userInfo) {

        User user = parseToUser(userInfo);
        if( user != null){
            return userMapper.save(user);
        }else {
            return -1;
        }

    }


    @Override
    public String findByPhoneAndPwd(String phone, String pwd) {

        User user = userMapper.findByPhoneAndPwd(phone, CommonUtils.MD5(pwd));

        if(user == null){
            return null;

        }else {
            String token = JWTUtils.geneJsonWebToken(user);
            return token;
        }

    }

    @Override
    public User findByUserId(Integer userId) {

        User user = userMapper.findByUserId(userId);
        return user;
    }

    /**
     * 解析 user 对象
     * @param userInfo
     * @return
     */
    private User parseToUser(Map<String,String> userInfo) {

        if(userInfo.containsKey("phone") && userInfo.containsKey("password") && userInfo.containsKey("username")){
            User user = new User();
            user.setUsername(userInfo.get("username"));
            user.setUserImg(getRandomImg());
            user.setCreateTime(new Date());
            user.setPhone(userInfo.get("phone"));
            String pwd = userInfo.get("password");
            //MD5加密
            user.setPassword(CommonUtils.MD5(pwd));

            return user;
        }else {
            return null;
        }

    }

    /**
     * 放在CDN上的随机头像
     */
    private static final String [] headImg = {
            "https://ccclass.oss-cn-beijing.aliyuncs.com/image_user/16218212686675093.jpg",
            "https://ccclass.oss-cn-beijing.aliyuncs.com/image_user/16218212847645048.jpg",
            "https://ccclass.oss-cn-beijing.aliyuncs.com/image_user/5416142845ce3ec630541197568142f3.jpeg",
            "https://ccclass.oss-cn-beijing.aliyuncs.com/image_user/7c2a556066c1419587f1397f41e60531.jpeg",
            "http://yun.flyskill.cn/view.php/2502ae6ec1d247ef9af689a2d1b9c195.jpeg",
            "http://yun.flyskill.cn/view.php/afabef4535c467e3051e3f535a09a4de.jpeg"
    };

    private String getRandomImg(){
        int size =  headImg.length;
        Random random = new Random();
        int index = random.nextInt(size);
        return headImg[index];
    }
}
